# app/user/crud/cruds.py
from collections.abc import Sequence

from sqlmodel import column

from app.core.handlers.database import SessionDep
from app.user.models.role import Role, RoleCreate
from app.user.models.user import User, UserCreate


class UserCRUD:
    """用户数据操作层"""

    def __init__(self, db: SessionDep):
        self.db = db

    async def get_user(self, user_id: int) -> User | None:
        """获取用户ORM对象"""
        user = self.db.select(User).where(User.id == user_id, User.is_deleted == False)
        return self.db.scalar(user)

    async def get_users(self, user_ids: str) -> Sequence[User]:
        """根据用户ID列表获取用户列表"""
        ids = [int(id_) for id_ in user_ids.split(",")]  # 确保ID是整数
        users = self.db.select(User).where(
            column("id").in_(ids), User.is_deleted == False
        )
        return self.db.scalars(users).all()

    async def get_user_by_username(self, username: str) -> User | None:
        """根据用户名获取用户ORM对象"""
        user = self.db.select(User).where(
            User.username == username, User.is_deleted == False
        )
        return self.db.scalar(user)

    async def create_user(self, user_data: UserCreate) -> User:
        """创建用户"""
        user = User(
            username=user_data.username,
            hashed_password=User.hash_password(user_data.password),
        )
        self.db.add(user)
        return user


class RoleCRUD:
    """角色数据操作层"""

    def __init__(self, db: SessionDep):
        self.db = db

    async def get_role(self, role_id: int) -> Role | None:
        """获取角色ORM对象"""
        role = self.db.select(Role).where(Role.id == role_id, Role.is_deleted == False)
        return self.db.scalar(role)

    async def get_roles(self, role_ids: str) -> Sequence[Role]:
        """根据角色ID列表获取角色列表"""
        ids = [int(id_) for id_ in role_ids.split(",")]  # 确保ID是整数
        roles = self.db.select(Role).where(
            column("id").in_(ids), Role.is_deleted == False
        )
        return self.db.scalars(roles).all()

    async def get_role_by_name(self, name: str) -> Role | None:
        """根据角色名获取角色"""
        role = self.db.select(Role).where(Role.name == name, Role.is_deleted == False)
        return self.db.scalar(role)

    async def create_role(self, role_data: RoleCreate) -> Role:
        """创建角色"""
        role = Role(name=role_data.name)
        self.db.add(role)
        return role
